<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /*
      https://leetcode-cn.com/problems/longest-common-prefix/
      https://leetcode-cn.com/problems/longest-common-prefix/solution/hua-jie-suan-fa-14-zui-chang-gong-gong-qian-zhui-b/
        思路：
      ● 当字符串数组长度为 0 时则公共前缀为空，直接返回
      ● 令最长公共前缀 ans 的值为第一个字符串，进行初始化
      ● 遍历后面的字符串，依次将其与 ans 进行比较，两两找出公共前缀，最终结果即为最长公共前缀
      ● 如果查找过程中出现了 ans 为空的情况，则公共前缀不存在直接返回
     */ 

    let strs = ["flower", "flow", "flight"];

    function longestCommonPrefix(strs) {
      if (strs === 0) return '';
      let ans = strs[0];

      for (let i = 1; i < strs.length; i++) {
        let j = 0; //因为后面要用到j
        for (; j < strs[i-1].length && j < strs[i].length; j++) {
          if (ans[j] !== strs[i][j]) break;
        }
        ans = ans.substring(0, j);
        if (ans === '') return '';
      }
      return ans;
    }
    console.log(longestCommonPrefix(strs));
  </script>
</body>
</html>